﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BankApplication.BusinessLogic;
using BusinessLogic.BusinessEntity.Entities;

namespace BankApplication.UI
{
	public partial class RoleForm : Form
	{
		public RoleForm()
		{
			InitializeComponent();
		}

		public void ValidateForm()
		{
			if (UserComboBox.SelectedIndex == -1)
			{
				throw new ValidationException("The user is not selected!");
			}

			if (RoleCombobox.SelectedIndex == -1)
			{
				throw new ValidationException("The role isn't selected!");
			}
		}

		private void AddButton_Click(object sender, EventArgs e)
		{
			try
			{
				ValidateForm();

				new ServerInteractionExceptionCatcher().Execute(() =>
				{
					var role = roles[RoleCombobox.SelectedIndex];
					var user = users[UserComboBox.SelectedIndex];

					UsersManager.AssignRole(user.ID, role, SessionManager.Instance.SessionTicket);
				});
				
				Close();
			}
			catch (ValidationException exception)
			{
				MessageBox.Show(exception.Message, "Form validation failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void cancelButton_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void UserComboBox_DropDown(object sender, EventArgs e)
		{
			new ServerInteractionExceptionCatcher().Execute(() =>
			{
				users = UsersManager.GetAllUsers(SessionManager.Instance.SessionTicket);
				var usersLogins = (from user in users select user.Login).ToList();
				UserComboBox.DataSource = usersLogins;
			});
		}

		private void RoleCombobox_DropDown(object sender, EventArgs e)
		{
			new ServerInteractionExceptionCatcher().Execute(() =>
			{
				roles = UsersManager.GetRoles();
				RoleCombobox.DataSource = roles;
			});
		}

		private IList<Role> roles;
		private IList<User> users;
	}
}
